import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

Vue.use(VueRouter);

const originalPush = VueRouter.prototype.push
//修改原型对象中的push方法
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}

const routes = [
    {
        path: '/',
        name: 'index',
        component: () => import('../views/Index.vue'),
        children: [
            {
                path: '/',
                name: 'home',
                component: () => import('../views/Home.vue'),
                meta: { title: '首页' }
            },
            {
                path: '/category/:cid',
                name: 'category',
                component: () => import('../views/Home.vue'),
                meta: { title: '分类' },
                props: true
            },
            {
                path: '/search/:words',
                name: 'search',
                component: () => import('../views/Home.vue'),
                meta: { title: '搜索' },
                props: true
            },
            {
                path: '/about',
                name: 'about',
                component: () => import('../views/About.vue'),
                meta: { title: '关于' }
            },
            {
                path: '/friend',
                name: 'friend',
                component: () => import('../views/Friend.vue'),
                meta: { title: '友链' }
            },
            {
                path: '/article/:id',
                name: 'article',
                component: () => import('../views/Articles.vue'),
                meta: {
                    title: '文章详情'
                },
                props: true
            }
        ]
    }
]

const router = new VueRouter({
    // mode: 'history',
    base: process.env.BASE_URL,
    routes
});

router.beforeEach((to, from, next) => {
    let title = 'Dblog'
    if (to.meta.params) {
        title = `${to.meta.title}:${to.params[to.meta.params] || ''} - ${title}`
    } else {
        title = `${to.meta.title} - ${title}`
    }
    document.title = title
    if (to.path !== from.path) {
        store.dispatch('setLoading', true);
    }
    next();
});

router.afterEach((to, from) => {
    // 最多延迟 关闭 loading
    setTimeout(() => {
        store.dispatch('setLoading', false);
    }, 300)
});

export default router
